﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using MagicKey.Components.AccessManager;
using MagicKey.Components.Database;
using MagicKey.Components.FileAccess;
using MagicKey.Components.UserManager;
using MagicKey.Factory;
using MagicKey.Interfaces;

namespace MagicKey.UserInterface
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Fields
        private Registration _registration;
        private Fileviewer _fileviewer;
        private MagicKeyFactory _factory = MagicKeyFactory.GetInstance();
        private IAccessManager _accessManager;
        private IDatabase _database;
        private string _masterUser;
        #endregion Fields

        #region Constructors
        public MainWindow()
        {
            InitializeComponent();
            Init();
        }
        #endregion Constructors

        #region Properties

        /// <summary>
        /// Gets and sets property of the _factory field.
        /// </summary>
        public MagicKeyFactory Factory
        {
            get
            {
                return this._factory;
            }

            set
            {
                this._factory = value;
            }
        }
        
        /// <summary>
        /// Gets and sets property of the _masterUser field.
        /// </summary>
        public string MasterUser
        {
            get
            {
                return this._masterUser;
            }

            set
            {
                this._masterUser = value;
            }
        }

        #endregion Properties

        #region Methods

        private bool AreBoxesNotEmpty()
        {
            bool boxesEmpty = (this.UsernameTextBox.Text == string.Empty && this.PasswordBox.Password == string.Empty);
            return !boxesEmpty;
        }
        #endregion Methods

        #region EventChangedMethods
        private void MainWindow_OnClosing(object sender, CancelEventArgs e)
        {
            string msg = "Exit the magic key?";
            MessageBoxResult result = MessageBox.Show(msg, "Magic key",
                MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.No)
            {
                // If user doesn't want to close, cancel closure
                e.Cancel = true;
            }
            else
            {
                e.Cancel = false;
            }
        }

        /// <summary>
        /// Invoked when an unhandled System.Windows.Input.Keyboard.KeyDown attached
        /// event reaches an element in its route that is derived from this class. Implement
        /// this method to add class handling for this event.
        /// </summary>
        /// <param name="keyEvent"> The System.Windows.Input.KeyEventArgs that contains
        /// the event data. </param>
        protected override void OnKeyDown(KeyEventArgs keyEvent)
        {
            if (keyEvent.Key == Key.Enter)
            {
                this.SignInButton_Click(new object(), new RoutedEventArgs());
            }
        }
        

        private void SignInButton_Click(object sender, RoutedEventArgs e)
        {
            string hashedPassword, savedPassword, salt;

            IMagicKey iMagicKey = _factory.GetMagicKeyInterface();

            this._accessManager = iMagicKey.GetAccessManager();

            this._masterUser = this.UsernameTextBox.Text.ToLower();

            if (AreBoxesNotEmpty())
            {
                hashedPassword = _accessManager.HashPassword(this.PasswordBox.Password);

                // Destroy a password
                this.PasswordBox.Password = null;

                // get salt from database
                this._database = iMagicKey.GetDatabase();
                //
                salt = this._database.LoadParameterUser("salt", this.UsernameTextBox.Text.ToLower());

                // Hash a hashed password with salt
                hashedPassword = _accessManager.HashHashedPasswordAndSalt(hashedPassword, salt);

                // Load saved password
                savedPassword = this._database.LoadParameterUser("password", this.UsernameTextBox.Text.ToLower());


                if (savedPassword != null && hashedPassword.Equals(savedPassword))
                {
                    this.WrongEntriesLabel.Visibility = Visibility.Collapsed;
                    this.Visibility = Visibility.Collapsed;
                    this._fileviewer = new Fileviewer(this);
                    this._fileviewer.Show();
                }
                else
                {
                    this.WrongEntriesLabel.Visibility = Visibility.Visible;
                }
            }
            else
            {
                String msg = "Please enter your username and password!";
                MessageBox.Show(msg, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void Init()
        {
            this.Visibility = Visibility.Visible;
            this.WrongEntriesLabel.Visibility = Visibility.Collapsed;
            this.UsernameTextBox.Text = string.Empty;
            this.PasswordBox.Password = string.Empty;
            this.Focus();
        }

        private void SignUpButton_Click(object sender, RoutedEventArgs e)
        {
            this.Visibility = Visibility.Visible;
            this._registration = new Registration(this);
            this._registration.ShowDialog();
        }

        #endregion EventChangedMethods

    }
}
